package com.neusoft.elmboot.service;

import java.math.BigDecimal;

import org.springframework.transaction.annotation.Transactional;

import com.neusoft.elmboot.mapper.UserWalletMapper;
import com.neusoft.elmboot.po.UserWallet;

public class VirtualWalletService {
	// 通过构造函数或者 IOC 框架注入  
    private UserWalletMapper userWalletMapper;  
    private VirtualWalletTransactionRepository transactionRepo;  
     
    public UserWallet getBalance(UserWallet walletId) {   
        return userWalletMapper.getUserWalletByIdByPass(walletId); 
    }  
    
    @Transactional
    public void debit(UserWallet walletId, Double amount) {
      UserWallet walletEntity = userWalletMapper.getUserWalletByIdByPass(walletId);
      VirtualWalletTransactionEntity transactionEntity = new VirtualWalletTransactionEntity();
      transactionEntity.setAmount(amount);
      transactionEntity.setCreateTime(System.currentTimeMillis());
      transactionEntity.setFromWalletId(walletId);
      transactionRepo.saveTransaction(transactionEntity);
      userWalletMapper.updateCredit(walletId.getUserId(), amount);
    }
    
    @Transactional
    public void credit(UserWallet walletId, Double amount) {
      UserWallet walletEntity = userWalletMapper.getUserWalletByIdByPass(walletId);
      VirtualWalletTransactionEntity transactionEntity = new VirtualWalletTransactionEntity();
      transactionEntity.setAmount(amount);
      transactionEntity.setCreateTime(System.currentTimeMillis());
      transactionEntity.setFromWalletId(walletId);
      transactionRepo.saveTransaction(transactionEntity);
      userWalletMapper.updateCredit(walletId.getUserId(), amount);
    }
    
    @Transactional
    public void transfer(UserWallet fromWalletId, UserWallet toWalletId, Double amount) {
      VirtualWalletTransactionEntity transactionEntity = new VirtualWalletTransactionEntity();
      transactionEntity.setAmount(amount);
      transactionEntity.setCreateTime(System.currentTimeMillis());
      transactionEntity.setFromWalletId(fromWalletId);
      transactionEntity.setFromWalletId(toWalletId);
      transactionRepo.saveTransaction(transactionEntity);
      debit(fromWalletId, amount);
      credit(toWalletId, amount);
    }

}
